import { useEffect, useRef } from 'react';
import { CSSTransition } from 'react-transition-group';
import { useLocation, useNavigate } from 'react-router-dom';
import './RouteTransition.css';

// 页面切换动画组件
const RouteTransition = ({ children }) => {
  const location = useLocation();
  const nodeRef = useRef(null);
  const navigate = useNavigate();
  
  // 点击链接时添加加载状态
  useEffect(() => {
    const handleLinkClick = (e) => {
      const link = e.target.closest('a[href^="/"]');
      if (link) {
        e.preventDefault();
        const targetPath = link.getAttribute('href');
        // 添加全局加载状态
        document.body.classList.add('page-transitioning');
        // 延迟跳转，确保动画能被感知
        setTimeout(() => {
          navigate(targetPath);
        }, 50);
      }
    };
    
    document.addEventListener('click', handleLinkClick);
    return () => {
      document.removeEventListener('click', handleLinkClick);
    };
  }, [navigate]);
  
  // 页面加载完成后移除过渡状态
  useEffect(() => {
    const timer = setTimeout(() => {
      document.body.classList.remove('page-transitioning');
    }, 300); // 与动画时长保持一致
    
    return () => clearTimeout(timer);
  }, [location.pathname]);

  return (
    <CSSTransition
      nodeRef={nodeRef}
      key={location.pathname}
      timeout={300}
      classNames="page-transition"
    >
      <div ref={nodeRef} className="page-container">
        {children}
      </div>
    </CSSTransition>
  );
};

export default RouteTransition;
    